<template>
  <div>
    <div>
      <!-- :o2m-todo="o2mTodo" -->
      <FormPage
        v-model="formData"
        :o2m-todo="o2mTodo"
        :data="dataDict"
        :options="options"
        :config="config"
      />

      <!-- <div>
        {{ formData }}
      </div> -->

      <!-- <div>
        {{ config.propForView }}
      </div> -->
    </div>
  </div>
</template>

<script>
import FormPage from '@/components/FormPage'
import objectMixin from './objectMixin'

// import api from '@/api'

export default {
  name: 'ObjetFormPage',
  components: { FormPage },
  mixins: [objectMixin],

  data() {
    return {
      model: '',
      formData: {},
      o2mTodo: {},
      fields: {}
    }
  },
  computed: {
    options() {
      return this.$store.state.object.options
    }
  },

  watch: {
    //
    // formData: {
    //   handler(newVal, oldVal) {
    //     // this.change()
    //     console.log('change, formData,', newVal.order_line, this.Model)
    //   },
    //   deep: true,
    //   immediate: true
    // }
  },

  async created() {
    this.init_header()
    this.init_fields()
    this.init_config()

    await this.init_formOptions()
    await this.init_data()
  },

  methods: {
    init_header() {
      // const model = this.model
      const Model = this.Model
      const { id } = this.$route.query
      const pageTitle = id ? '编辑' : '创建'

      // header title
      this.$store.dispatch(
        'header/setTitle',
        `${pageTitle}  ${Model.metadata.description}`
      )
    },

    init_fields() {
      const fields = this.get_fieldsForBrowse()
      this.fields = fields
    },

    async init_formOptions() {
      //
      const model = this.model
      const Model = this.Model
      const fields = Model.metadata.fields
      const fs = Object.keys(fields).reduce((acc, cur) => {
        if (['many2one', 'selection'].includes(fields[cur].type)) {
          acc[cur] = { fields: fields[cur].fields }
        } else if (['many2many'].includes(fields[cur].type)) {
          if (fields[cur].selected) {
            acc[cur] = { fields: fields[cur].fields }
          }
        }

        return acc
      }, {})

      console.log('init_formOptions,', fs)
      await this.$store.dispatch('object/get_options', {
        _model: model,
        fields: fs
      })
      console.log('init_formOptions 2,', this.$store.state.object.options)
    },

    async init_data() {
      const model = this.model

      const { id } = this.$route.query

      // data
      if (id) {
        const rid = Number(id)
        await this.$store.dispatch('object/browse_one', {
          _model: model,
          id: rid,
          fields: this.fields
        })

        const Model = this.Model

        const formData = this.$store.state.object.formData
        const dataDict = this.$store.state.object.dataDict
        const metadata = Model.metadata.fields
        // console.log('metadata', metadata)

        const o2mTodo = {}

        this.formData = Object.keys(formData).reduce((acc, cur) => {
          // console.log('xxxxxx, formData,', cur)
          const meta = metadata[cur]
          // console.log('meta', cur, meta)
          if (cur === 'display_name') {
            // do nothing  display_name
            console.log('xxxxxx, formData,', cur)
          } else if (!meta) {
            acc[cur] = formData[cur]
          } else if (cur === 'id') {
            acc[cur] = formData[cur]
          } else if (
            ['one2many', 'many2many'].includes(meta.type) &&
            meta.selected !== true
          ) {
            //
            o2mTodo[cur] = [...dataDict[`${cur}__objects`]]
            acc[cur] = []
          } else {
            acc[cur] = formData[cur]
          }
          return acc
        }, {})

        this.o2mTodo = o2mTodo

        // console.log('xxxxxx, metadata,', Model.metadata.fields)
        // console.log('xxxxxx, formData,', formData)
        console.log('xxxxxx, formData,', this.formData)
        // console.log('xxxxxx, o2mTodo,', o2mTodo)
        // console.log('xxxxxx, dataDict,', dataDict)
      }
    },

    async onSubmit(values) {
      //
      console.log('onSubmit', values)
      const { id } = values
      if (id) {
        const action = `object/write`
        await this.$store.dispatch(action, {
          _model: this.model,
          values,
          fields: this.fields
        })
        this.$router.back()
      } else {
        const action = `object/create`
        const res = await this.$store.dispatch(action, {
          _model: this.model,
          values,
          fields: this.fields
        })
        this.$router.replace({
          path: this.config.path.view,
          query: { model: this.model, id: res.id }
        })
      }
    },

    async onDelete(values, cb) {
      const { id } = values
      if (id) {
        const action = `object/unlink`
        await this.$store.dispatch(action, { _model: this.model, id })
      }
      if (cb) {
        cb()
      }
      this.$router.back()
      this.$router.back()
    }
  }
}
</script>

<style type="text/css"></style>
